<template>
  <div class='box-wrap'>
    <section class='box-operation'>
      <div class="box-search">
        <div class='form-group-enquire'>
          <el-select v-model="searchData.menu_name" placeholder="全部项目菜单" clearable filterable>
            <el-option :value= row.name v-for="(row,i) in menuList" :label= row.title :key= i >{{row.title}}</el-option>
          </el-select>
        </div>   
        <div class='form-group-enquire'>
          <DatePicker type="daterange" placeholder="日期" style="width: 190px" :editable=false  v-model="searchDate" @on-change="changeDate" @on-clear="initDate"></DatePicker>
        </div>        
        <div class='form-group-img' @click='onSearchGetList()'><img src="../../assets/images/peach-svg/Frame 23.svg"></div>
        <div class='form-group-addimg' @click='editInfo(1,{})'><img src="../../assets/images/peach-svg/add.svg"></div>
      </div>
    </section>
    <LibVxeTable class="staticData" :stripe="stripe" :tableColumns="tableColumns" border="none" :tableData="list" :slotHeader="slotHeader" :PageObj="{total:totalCnt,currentPage:searchData.page_index,pageSize:searchData.page_size}"  @onPageChange="onChangePageSize" resizable></LibVxeTable>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import {commonMixin} from "../../components/ViewInitMixin" //每一个文件都要包含这个
import {TimePicker} from "iview"
import SearchUser from "../searchUser"
import Request from "../../commons/Request"

export default {
  name: "addUserDetailView",  //!!这块一定要注意，每一个文件都根据资源path来命名
  components:{TimePicker,SearchUser},
  mixins:[commonMixin],
  data() {
    const validateMenu = (rule, value, callback) =>{
      if(value == ""){
        callback(new Error("项目菜单必须选择"));
      }else {
        callback();
      }
    };
    return {
      stripe:false,      
      statuslist: [{id:1,name:'启用'},{id:2,name:'禁用'}],
      modal:false,
      searchDate:"",
      searchTime:[utils.dateFormat(0,"HH")+"00",utils.dateFormat(0,"HH")+"00"],
      searchData:{
        // account:"",
        menu_name:"",
        start:"",
        end:"",
        page_index:1,
        page_size:30,
      },
      versionsList:[{Id:-1,Name:'全部版本'},{Id:1,Name:'v1'},{Id:2,Name:'v2'}],
      mnoList:{},
      provinceList:{},
      list:[],
      totalCnt:0,
      info:{},
      channelList:[],
      cityList:[],
      cityInfo:[-1],
      partnerList:[],
      ChannelList:[],
      QdsPartnerList:[],
      QdsPartnerObj:{},
      BusinessList:[],
      BusinessObj:{},
      cityObj:{},
      brandObj:{},
      brandObjCh:{},
      searchTime:['00:00','23:59'],
      formPopIndex:0,
      roles:[],
      leaders:[],
      roleObj:{},
      menuList:[],
      leaderlist:[],
      tableColumns:[
        {
          title: "项目菜单",
          field: "menu_name",
          align: 'center',
        },
        {
          title: "标题说明",
          field: "title",
          align: 'center',
        },
        {
          title: "展示内容",
          field: "content",
          align: 'center',
          width: 206,
          slots:{
            default:({row},h)=>{
              let conten=row.content
              if((conten!=''||conten!=undefined)&& String(conten).length>15){
                conten= conten.substring(0,20)+'...'
              
              return [h("el-tooltip",
              {
                props: { placement: "right"},
              },
              [h("span",
                  {
                    style: {
                      whiteSpace: "nowrap",
                      textOverflow: "ellipsis",
                      width: "56px",
                    },
                  },conten
                ),
                h("div",
                    {
                      slot: "content",
                      style: {
                        padding: "10px",
                        width:"200px",
                        maxWidth: "200px",
                        minWidth:"2px"
                      },                  
                    },
                    [h("span",{
                        style:{
                            size: "15px",
                          }
                        },row.content
                    )]
                ),
              ]
              )]}else{
                return[h("div"),row.content]
              }
            }
          }            
        },
        {
          title: "状态",
          field: "status",
          align: 'center',
          slots: {
                default: ({row},h) => {
                    let disabled = false;
                    if(this.Perm.add){
                        disabled = false;
                    }
                    return [h("iSwitch",
                            {
                                props: {
                                value:(1 & row.status)==1?true:false,
                                disabled:disabled,
                                size:"large",
                                },
                                on: {
                                'on-change': (value) => {
                                    let info = {"id":row.id};
                                    value==true?this.handleType = 3:this.handleType = 4;
                                    this.updateInfo(info);
                                }
                                }
                            },
                            [
                                h('span', {
                                slot: 'open',
                                domProps: {
                                    innerHTML: '启用'
                                }
                                }),
                                h('span', {
                                slot: 'close',
                                domProps: {
                                    innerHTML: '禁用'
                                }
                                })
                            ]
                    )];
                }
            }
        },
         {
          title: "创建时间",
          field: "create_at",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.create_at==0){
                return [h("div",'-')]
              }else
              return [h("div",utils.dateFormat(row.create_at,"yyyy-MM-dd HH:mm:ss"))]
            }
          }
        },{
          title: "修改时间",
          field: "updated_at",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.updated_at==0){
                return [h("div",'-')]
              }else
              return [h("div",utils.dateFormat(row.updated_at,"yyyy-MM-dd HH:mm:ss"))]
            }
          }
        },
        {
          title: "修改人",
          field: "creator_name",
          align: 'center',
        },
        {
          title: "操作",
          field: "action",        
          width: 150,
          align: "center",
          slots:{
            default: ({row},h) => {
              return this.$AutoFun(()=>{
              let hButton = [];

                hButton.push(h(
                    "div",
                    {
                      class:"two",
                      on: {
                        click: () => {
                          this.editInfo(2,row);
                        }
                      }
                    },
                  ));
                hButton.push(
                  h(
                    "div",
                    {
                      class:"three",
                      on: {
                        click: () => {
                          this.sureDel(row,-1);
                        }
                      }
                    },
                  )
                );
              return hButton;
            });
            }
          }
        }
      ],
      format: {  
        menu_name:{
          labelName: "项目菜单",
          labelType: "select",  
          labelValue: [],    
          placeholder:"请选择项目菜单"
        },
        title:{
          labelName: "标题说明",
          labelType: "text",     
          placeholder:"请输入标题说明"          
        },
        content:{
          labelName: "展示内容",
          labelType: "textarea",        
          placeholder:"请输入展示内容" 
        },              
      },     
      ruleValidate: {
        menu_name: [{ required: true,validator:validateMenu, trigger: "blur" }],
        title: [{ required: true,message: "标题说明不能为空", trigger: "blur" }],
      },      
      dateOptions:{
        disabledDate(date){
          return date && date.valueOf() > Date.now();
        },

      },
    };
  },
  computed: {
            ...mapGetters(["UserInfo"]),
        },
  methods: {
    async initView(isMounted){
      if(isMounted){
        this.initDate();
        await this.getList();
        await this.initSearchData();
      }

    },
    async initSearchData() {
      let leaders = await Request.post("sys/menu","queryMenu_list",{"level":2})
      if(leaders.data!=null){
        leaders.data.forEach((item) => {
          this.menuList.push(item)
          this.format.menu_name.labelValue.push({"id":item.name,"name":item.title})
        })        
      } 
    },
    onSearchGetList(){
      this.searchData.page_index =1;
      this.getList();
    },
    async getList(){
      utils.showLoading()
      let res = await this.RequestPost("query_list",this.searchData); 
      if(res.code==0 && res.data != null){
        this.list = [];
        if(res.data.list!=null) this.list = res.data.list;
        this.totalCnt = res.data.total
      }
      await utils.sleepMs(500)
      utils.hideLoading();
    },    
    async updateInfo(info) {
      utils.showLoading()
      let code = -1;
      let actionName = '';
      let tipText = '';
      let postData = utils.cloneObj(info);
      if (this.handleType==1) {
        actionName = 'add_item';
        tipText = '添加成功！';    
      }else if(this.handleType==2){
        actionName = 'edit_item';
        tipText = '编辑成功！';     
      }else if(this.handleType==-1){
        actionName = 'del_item';
        tipText = '删除成功！';
        postData = {"id":postData.Id};
      }else if(this.handleType==3){
        actionName = 'enable_item';
        tipText = '启用成功！';
        postData = {"id":postData.id};
      }else if(this.handleType==4){
        actionName = 'disable_item';
        tipText = '禁用成功！！';
        postData = {"id":postData.id};
      }
      let res = await this.RequestPost(actionName, postData);
      code = res.code;
      if (code == 0) {
        utils.hideFormPage(this.formPopIndex);
        await utils.sleepMs(1000);
        this.onSearchGetList();
        utils.showTip(tipText);
      }
      utils.hideLoading();
    },    
    //添加 编辑用户
    async editInfo(type,row) {
      this.handleType=type;
      let title = "";
      let info = {};
      if(this.handleType==1){
        title = "添加提示";
        info = {
          menu_name:"",          
          title:"",
          content:"",
          number_bit_count:"",
        };
      }else{
        if (row.Status > 1){
          this.format.Status.labelDisabled = true
        }
        title = "编辑提示";
        info = {
          id:row.id,
          menu_name:"自定义号码生成2",    
          title:row.title,
          number_bit_count:row.number_bit_count,      
          content:row.content,         
        };
      }
      this.formPopIndex=await utils.showFormPage(
        { title: title,el:this.$parent.$el,width:700,cancelBtnStatus:0},
        info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
        this.onSelectChange,
      );
    },    
    //删除
    sureDel(item,type) {
       this.handleType = -1;
        utils.shadowModel(
          {
            "title":"删除提示",            
            "icon":require('../../assets/images/peach-svg/Frame 427318277 (1).svg'),            
            "modalContent":"确认删除 "+item.title+" ?",
            "callBackArgs":{"Id":item.id}},(res)=>{
        let code = res.code;
        if(code==0){
          let data = res.data;
          this.updateInfo(data);
        }
      });
      this.getList()
    },    
    onChangePageSize(page,pageSize){
      this.modal = true        
      this.searchData.page_index = page;
      this.searchData.page_size = pageSize;
      this.getList();
    },
    changeDate(){
      // this.searchTime.forEach((item,index)=>{
      //     let hour = item.split(":")[0]
      //     this.searchDate[index].setHours(hour);
      //     if(index==1){
      //       this.searchDate[index].setMinutes(59)
      //       this.searchDate[index].setSeconds(59)
      //     }
      //   })
      this.searchData.start = Date.parse(this.searchDate[0])/1000;
      this.searchData.end = Date.parse(this.searchDate[1])/1000+86400+86400;
      this.onSearchGetList();
    },
    initDate(){
      let nowDay = ""
      let beginDay = nowDay;
      let endDay = nowDay;
      this.searchDate = [new Date(beginDay),new Date(endDay)];
      this.changeDate();
    },
    onSelectChange(label,value,reset){
      // this.format.Name.labelValue = []
     
      // if(label=="CompanyId"){
      //   this.isSelectCompany = value
      // }
      // if(label=="DepartmentId"){
      //   this.isSelectDepartment = value
      // }
      // if(label=="GroupId"){
      //   this.isSelectGroup = value
      // }
      // if(label=="Name"){
      //   this.isSelectName = value
      // }
      // if(label=="PurchaseType"){
      //   this.PurchaseType1 = 0
      //   this.PurchaseType2 = 0
      //   this.PurchaseType1 = parseInt(value["0"])
      //   this.PurchaseType2 = parseInt(value["1"])
      // }
      // this.userlist.forEach((item) => {
      //   if(item.Company == this.isSelectCompany && item.Department == this.isSelectDepartment && item.Group == this.isSelectGroup ) {
      //     this.format.Name.labelValue.push({id:item.Id,name:item.Name});
      //   }
      // })
    },    
    slotHeader(h) {
      return [h("div",{class:{"allCount":true},"style":{"margin-left":"10px"}})]
    },
    filterPartner(item){
      if (item.Id == -1) return true;
      if (this.searchData.searchBusinessId == -1 ) return true
        return item.BusinessId==this.searchData.searchBusinessId;
    },
  },
};
</script>  